package cn.bdqn.service.impl;

import cn.bdqn.dao.ProductDao;
import cn.bdqn.dao.SaleDao;
import cn.bdqn.entity.Sale;
import cn.bdqn.enums.JxcEnum;
import cn.bdqn.exception.JxcException;
import cn.bdqn.service.ProductService;
import cn.bdqn.service.SaleService;
import com.github.pagehelper.PageException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author 郑大仙丶
 * @date 2018-12-31 13:52
 */
@Service
public class SaleServiceImpl implements SaleService {

    @Autowired
    private SaleDao saleDao;

    @Autowired
    private ProductService productService;


    // 添加销售记录功能.
    @Override
    @Transactional
    public void save(Sale sale) {
        //1. 减少商品的库存.
        productService.decreaseQuantity(sale.getProductId(),sale.getQuantity());
        //2. 计算商品的总价.
        Integer quantity = sale.getQuantity();
        BigDecimal price = sale.getPrice();
        BigDecimal totalPrice = price.multiply(new BigDecimal(quantity));
        sale.setTotalPrice(totalPrice);
        //3. 保存
        Integer count = saleDao.save(sale);
        if(count != 1){
            throw new JxcException(JxcEnum.SALE_ADD_ERROR);
        }
    }

    // 分页查询并根据条件排序.
    @Override
    public PageInfo<Sale> findAllOrderBy(
            Integer page,
            Integer size,
            Integer flag) {
        //1. 分页.
        PageHelper.startPage(page,size);
        //2. 查询.
        List<Sale> list = saleDao.findAllOrderBy(flag);
        //3. 封装数据
        PageInfo<Sale> pageInfo = PageInfo.of(list);
        //4. 返回
        return pageInfo;
    }
}
